<template>
  <div class="normalMaintenanceStandardDetails h100">
    <editPageNew
      ref="editPage"
      :rightBtnArr="rightBtnArr"
      :stepConfig="stepConfig"
      :creatInfo="formData"
      :moreBtnArr="moreBtnArr"
      :showMore="pageType != 'add'"
      showTopTitle
    >
      <template slot="editPageTitle">
        <span class="title-code"> 试验标准 {{ formData.code || "" }}</span>
      </template>
      <div class="plan-title">
        <div v-show="!showInput" class="name">
          <span style="color: red"></span>
          <span>{{ titleName }}</span>
          <el-link
            v-show="titleEdit"
            style="font-size: 20px"
            icon="el-icon-edit-outline"
            @click="editTitle"
          ></el-link>
        </div>
        <div v-show="showInput" class="name-input">
          <!-- <label>参数组名称</label> -->
          <el-input
            type="text"
            v-model="titleName"
            maxlength="64"
            show-word-limit
            @blur="loseFocus"
            placeholder="请输入名称"
            clearable
            ref="mark"
            ><template slot="prepend" style="color: red"
              >标题</template
            ></el-input
          >
        </div>
      </div>
      <dividerTitle :title="'基本信息'"></dividerTitle>
      <baseInfo :baseInfo="formData" :unEdit="unEdit" ref="baseInfo" />
      <div class="select">
        <el-row>
          <el-col :span="6" style="display: flex">
            <label class="item-label">作业步骤层数</label>
            <el-select
              class="input"
              size="mini"
              v-model="stepLevel"
              placeholder="请选择"
              @change="selectStepLevel"
              :disabled="unEdit"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-col>
        </el-row>
      </div>
      <test
        :data="tableData"
        :isEditTable="isEditTable"
        :hideBtn="unEdit"
        :stepLevel="stepLevel"
        ref="tableParam"
      />
      <div class="upload-file">
        <h3>试验报告模板：</h3>
        <el-button
          v-if="!unEdit"
          class="btn-text-blue"
          plain
          size="mini"
          @click="design"
          icon="el-icon-edit-outline"
          >设计</el-button
        >
        <el-button
          v-else
          class="btn-text-blue"
          plain
          size="mini"
          @click="search"
          icon="el-icon-view"
          >查看</el-button
        >
      </div>
    </editPageNew>
  </div>
</template>
<script>
import test from "../normalMaintenanceStandard/test.vue";
import baseInfo from "./baseInfo.vue";
import {
  queryExperimentDetail,
  addExperiment,
  updateExperiment,
  setExperimentStatus,
  deleteExperiment,
  designExperiment,
  previewExperiment,
} from "@/api/standardManagement/operateStandard.js";
import {
  getAttachList, //附件列表获取
} from "@/api/common";
export default {
  components: { test, baseInfo },
  data() {
    return {
      titleName: "",
      showInput: false,
      isEditTable: true,
      titleEdit: true,
      formData: {
        envParams: [],
        deviceParams: [],
      },
      moreBtnArr: [
        {
          text: "操作记录",
          methods: () => {
            this.$refs.editPage.showOperate();
          },
        },
      ],
      stepLevel: 1,
      options: [
        { label: "1", value: 1 },
        { label: "2", value: 2 },
      ],
      tableData: [],
      option: {
        1: "Ⅰ",
        2: "Ⅱ",
        3: "Ⅲ",
      },
      filesList: [],
    };
  },
  computed: {
    rightBtnArr() {
      let arr = [
        {
          text: "发布",
          icon: "el-icon-position",
          hide:
            ["details", "perform", "add"].includes(this.pageType) ||
            this.formData.status != 0,
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("release"),
          methods: () => {
            this.release();
          },
        },
        {
          text: "取消发布",
          icon: "icon-quxiaofabu",
          hide: this.formData.status != 1,
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("unRelease"),
          methods: () => {
            this.unRelease();
          },
        },
        {
          text: "保存",
          icon: "el-icon-check",
          hide:
            ["details", "perform"].includes(this.pageType) ||
            this.formData.status == 1,
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("save"),
          methods: () => {
            this.save();
          },
        },
        {
          text: "删除",
          icon: "el-icon-delete-solid",
          hide:
            ["perform", "add"].includes(this.pageType) ||
            this.formData.status == 1,
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("delete"),
          methods: () => {
            this.deleteId();
          },
        },
      ];
      return arr;
    },
    stepConfig() {
      let obj = {
        nowStep: this.formData.status, //当前步骤，对应stepItem数组的下标，例如：0-步骤一、1-步骤二
        stepItem: ["草稿", "已发布"],
      };
      return obj;
    },
    unEdit() {
      return (
        ["query", "detail"].includes(this.pageType) || this.formData.status == 1
      );
    },
  },
  created() {
    this.init();
  },
  mounted() {},
  methods: {
    //初始化详情页
    init() {
      let { id } = this.$route.query;
      if (id) {
        //this.pageType = "edit";
        this.pageType = this.$store.getters.isBtnAuth("edit")
          ? "edit"
          : "detail";
        this.getDetails(id);
        if (this.pageType == "detail") {
          this.basicConfig.itemArr.map((i) => (i.disabled = true));
          this.titleEdit = false;
          this.isEditTable = false;
        }
      } else {
        this.pageType = "add";
        this.showInput = true;
        this.$set(
          this.formData,
          "appid",
          this.$store.state.user.userInfo.appId
        );
        this.$set(
          this.formData,
          "appName",
          this.$store.state.user.userInfo.appName
        );
      }
    },
    //编辑标题
    editTitle() {
      this.showInput = true;
      setTimeout(() => {
        this.$refs.mark.focus();
      }, 0);
    },
    //失去焦点
    loseFocus() {
      if (this.titleName != "") {
        this.showInput = false;
      } else {
        this.$message.warning("名称不能为空");
      }
    },
    //选择作业步骤层级
    selectStepLevel(val) {
      //this.$refs.tableParam.clearTableData();
    },
    //获取标准详情
    getDetails(id) {
      queryExperimentDetail({ id: id }).then((res) => {
        if (res.code == 200) {
          this.formData = res.data;
          this.titleName = this.formData.name;
          this.stepLevel = res.data.stepLevel;
          if (this.formData.status) {
            this.isEditTable = false;
            this.titleEdit = false;
          } else {
            this.isEditTable = true;
            this.titleEdit = true;
          }
          if (res.data.itemDTOs.length != 0) {
            let data = JSON.parse(JSON.stringify(res.data.itemDTOs));
            let arr = this.initTableData(data);
            this.tableData = arr;
          }
        }
      });
    },
    //获取附件列表
    getFileList(id) {
      getAttachList({ businessId: id }).then((res) => {
        if (res.code == 200) {
          this.filesList = res.data;
        }
      });
    },
    //设计模板
    design() {
      if (this.pageType == "add") {
        this.$message.warning("请先保存试验标准");
      } else {
        let param = {
          standardId: this.formData.id,
          standardName: this.formData.name,
        };
        designExperiment(param).then((res) => {
          let token = localStorage.getItem("GDH_WATER_TOKEN");
          let dataSource = "_default";
          let org = localStorage.getItem("currOrg");
          let leader = localStorage.getItem("currLeader");
          let leaderOrg = localStorage.getItem("currLeaderOrg");
          let url = `${res.data}&token=${token}&dynamicDataSource=${dataSource}&dynamicOrg=${org}&dynamicLeader=${leader}&dynamicLeaderOrg=`;
          if (leaderOrg) {
            url = `${url}${leaderOrg}`;
          }
          this.$utils.isInstallPrintSoftware(url);
        });
      }
    },
    //查看模板
    search() {
      let param = {
        standardId: this.formData.id,
      };
      previewExperiment(param).then((res) => {
        let token = localStorage.getItem("GDH_WATER_TOKEN");
        let dataSource = localStorage.getItem("currDs");
        let org = localStorage.getItem("currOrg");
        let leader = localStorage.getItem("currLeader");
        let leaderOrg = localStorage.getItem("currLeaderOrg") || null;
        let url = `${res.data}&token=${token}&dynamicDataSource=${dataSource}&dynamicOrg=${org}&dynamicLeader=${leader}&dynamicLeaderOrg=${leaderOrg}`;
        this.$utils.isInstallPrintSoftware(url);
      });
    },
    //发布
    async release() {
      try {
        let formData = await this.$refs.baseInfo.getFormInfo();
        let tableData = this.$refs.tableParam.getTableData();
        formData.stepLevel = this.stepLevel;
        formData.itemDTOs = tableData;
        formData.name = this.titleName;
        formData.status = 1;
        let res;
        if (formData.name == "") {
          this.$message.warning("标题名称不能为空");
        } else if (!tableData) {
          return;
        } else {
          this.$confirm("请确认试验报告模板设计完成", "提示", {
            confirmButtonText: "继续发布",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(async () => {
              res = await updateExperiment(formData);
              this.$utils.addOperateLog(this.formData.id, `发布了试验标准`);
              this.$message.success(res.description);
              this.getDetails(this.formData.id);
              this.updateListData();
            })
            .catch((e) => {});
        }
      } catch (error) {}
    },
    //取消发布
    unRelease() {
      const params = {
        id: this.formData.id,
        status: 0,
      };
      setExperimentStatus(params).then((res) => {
        if (res.code == 200) {
          this.$message.success("取消发布成功");
          this.$utils.addOperateLog(this.formData.id, `取消发布了试验标准`);
          this.getDetails(this.formData.id);
          this.updateListData();
        }
      });
    },
    deleteId() {
      this.$confirm("确定要删除选中数据吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteExperiment({ ids: this.formData.id }).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.description);
              this.updateListData();
              this.$refs.editPage.closePage();
            }
          });
        })
        .catch((e) => {});
    },
    //保存试验标准
    async save() {
      try {
        let formData = await this.$refs.baseInfo.getFormInfo();
        let tableData = this.$refs.tableParam.getTableData();
        formData.stepLevel = this.stepLevel;
        formData.itemDTOs = tableData;
        formData.name = this.titleName;
        formData.status = 0;
        let res;
        if (formData.name == "") {
          this.$message.warning("标题名称不能为空");
        } else if (!tableData) {
          return;
        } else {
          if (this.pageType == "add") {
            res = await addExperiment(formData);
            this.$message.success(res.description);
            this.$utils.addOperateLog(res.data, `新建了试验标准`);
            this.updateListData();
            let obj = {
              id: res.data,
              pageType: "edit",
            };
            this.$router.push({
              query: obj,
            });
            //this.getDetails(this.res.data);
          } else {
            res = await updateExperiment(formData);
            this.$message.success(res.description);
            this.$utils.addOperateLog(this.formData.id, `修改了试验标准`);
            this.getDetails(this.formData.id);
            this.updateListData();
            this.$alert("标准更改后请重新设计模板", "", {
              confirmButtonText: "确定",
              center: true,
            });
          }
        }
      } catch (error) {
        console.log(error);
      }
    },
    /* 更新列表页的数据 */
    updateListData() {
      /* 通过localStorage来实现浏览器不同窗口之间的通信 */
      let num = Math.floor(Math.random() * 1000) + 1; //产生随机数，保证每次的值都不一样
      localStorage.setItem("update", num); //设置localStorage里面的值，保证每次都会触发storage事件
    },
    //判断表格必填项
    handleTbaleData(data) {
      let isComplete = true;
      data.forEach((item, i) => {
        item.context == "" && (isComplete = false);
        if (item.children.length != 0) {
          item.children.forEach((child, index) => {
            child.context == "" && (isComplete = false);
          });
        }
      });
      return isComplete;
    },
    //处理详情页的表格数据
    initTableData(data) {
      let arr = data.map((item, i) => {
        item.edit = false;
        item.sort = i + 1;
        item.rowIndex = i;
        item.levelabel = this.option[item.level];
        item.itemParamString = this.customsHandleConfirm(item.itemParams);
        if (item.children.length != 0) {
          item.children.forEach((child, index) => {
            child.edit = false;
            child.parentId = item.id;
            child.rowIndex = index;
            child.sort = `${i + 1}.${index + 1}`;
            child.levelabel = this.option[child.level];
            child.itemParamString = this.customsHandleConfirm(child.itemParams);
          });
        }
        return item;
      });
      return arr;
    },
    //通过逗号把list的值拼接起来
    customsHandleConfirm(list) {
      let string = "";
      list.forEach((item, i) => {
        if (i == 0) {
          string += `${item.name}(${item.unit})`;
        } else {
          string += `,${item.name}(${item.unit})`;
        }
      });
      //通过逗号把几个输入框的值拼接起来
      return string;
    },
  },
};
</script>
<style lang="less" scoped>
.normalMaintenanceStandardDetails {
  // overflow: hidden;

  background-color: #ffffff;
  .TitleImg {
    margin-right: 2px;
    font-size: 22px;
  }
  .plan-title {
    height: 40px;
    margin: 0 0 10px 0;
    .name {
      font-size: 18px;
      padding: 0 10px;
      height: 40px;
      font-weight: bold;
      line-height: 40px;
      text-align: left;
      padding: 0 10px;
    }
    .name-input {
      width: 400px;
      height: 40px;
      line-height: 40px;
    }
  }
  .select {
    margin: 10px 0 20px 0px;
    .item-label {
      font-size: 14px;
      padding-right: 8px;
    }
    .item-label::before {
      content: "*";
      color: red;
      margin-right: 4px;
    }
    .input {
      width: calc(100% - 102px);
    }
  }
  .upload-file {
    margin-top: 30px;
    text-align: left;
    display: flex;
    h3 {
      margin-right: 10px;
      font-size: 14px;
    }
  }
}
</style>